package com.googlecode.bip.xml.export;

import java.sql.SQLException;
import java.util.List;
import javax.naming.NamingException;

/**
 * @author Claude
 *
 */
//not public
class XMLQuestionFactory extends XMLSurveyEntryFactoryBuilder<XMLQuestion>
{
    private static final long serialVersionUID = 1L;

    protected XMLQuestionFactory(
            XMLSurveyConnection connection,
            String              sql
            )
    {
        super( connection, sql );
    }

    /**
     * TODO: doc
     *
     * @param parentidtopic
     * @return
     * @throws SQLException
     * @throws NamingException
     */
    public static List<XMLQuestion> createList(
            XMLSurveyConnection connection,
            int                 idtopic
            )
        throws SQLException, NamingException
    {
        StringBuilder sql = new StringBuilder();
        sql.append( "SELECT * FROM `questions` WHERE `idtopic`" );

        if( idtopic == 0 ) {
            sql.append( " IS NULL;" );
            }
        else {
            sql.append( '=' ).append( Integer.toString( idtopic ) ).append( ';' );
            }
        XMLQuestionFactory xml = new XMLQuestionFactory( connection, sql.toString() );
        //ResultSet rset = xml.execute();
        XMLSurveyConnection.ResultSetCache rset = xml.execute(
                "idquestion",
                "order",
                "isactive",
                "minvalue",
                "maxvalue",
                "defaultvalue"
                );

        try {
            while( rset.next() ) {
                int idquestion      = rset.getInt( "idquestion" );
                int order           = rset.getInt( "order" );
                int isactive        = rset.getInt( "isactive" );
                int minvalue        = rset.getInt( "minvalue" );
                int maxvalue        = rset.getInt( "maxvalue" );
                int defaultvalue    = rset.getInt( "defaultvalue" );

                xml.add( new XMLQuestion( connection, idquestion, order, isactive, minvalue, maxvalue, defaultvalue ) );
                }
            }
        finally {
            rset.close();
            }

        return xml.getList();
    }

}
